#include<iostream>
#include<string>
#include<stack>
#include<queue>
using namespace std;

class myclass{
private:
    int* age;
    string name;
public:
    myclass(int age,string name):name(name),age(new int(age)){}
    ~myclass(){
        delete age;
        age=nullptr;
    }
};
class memoryPool{
public:
//构造函数与析构函数
    memoryPool(size_t obj_sz,size_t total_sz):obj_size(obj_sz),total_size(total_sz){
        pool=new char[obj_sz*total_sz];
        for(int i=0;i<total_sz;i++){
            mem_list.push(pool+obj_sz*i);
        }
    }
    ~memoryPool(){
        delete pool;
        pool=nullptr;
        cout<<"total allocate "<<count_time<<" times memory during the lifespan"<<endl;
    }
//分配与回收函数
    void* allocation(){
        count_time++;
        if(mem_list.empty()){
            cout<<"the "<<count_time<<" allocation failed"<<endl;
            count_time--;
            throw bad_alloc();
        }    
        cout<<"the "<<count_time<<" allocation succeed"<<endl;
        void* p=mem_list.top();
        mem_list.pop();
        return p;
    }
    void recycle(void* p){
        mem_list.push(p);
    }

private:
    static int count_time;
    size_t obj_size;
    size_t total_size;
    char* pool;
    stack<void*> mem_list;
};


int memoryPool::count_time = 0;

int main(){
    memoryPool pool(sizeof(myclass),3);
    queue<void*> lists;
    try{
        for(int i=0;i<4;i++){
            lists.push(pool.allocation());
        }           
    }catch(bad_alloc &e){
        while(!lists.empty()){
            void *p=lists.front();
            lists.pop();
            myclass *my=new(p) myclass(5,"chenjunfu");
            my->~myclass();
            pool.recycle(p);
            /*
                上面两行代码是线程池的核心
                内存是内存池所有的，所以不能free my指针
                为了避免旧对象和新对象共用内存，所以显示地调用析构函数
            */
        }
        return 1;
    }
    return 0;
}